/*
 * ProjectNew.java
 *
 * Created on June 7, 2007, 9:00 PM
 * 25, Oct 2009: Some modifications in order to move entities to the correct objects to handle (time related to TimeLine object, etc.)
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package portfolio.dbHost;

/**
 *
 * @author ACA
 */

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.util.Calendar;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.tree.*;
import java.sql.*;
import misellanea.Miscellanea;
import portfolio.dbHost.dataBases.DBase;
import portfolio.dbHost.dataBases.dbTable.Table;
import portfolio.dbHost.dataBases.dbTable.tblColumn.Column;
import portfolio.dbHost.project.Project;
import portfolio.dbHost.project.attributes.ExcludeColumns;
import portfolio.dbHost.project.attributes.ExcludeTables;
import portfolio.dbHost.project.attributes.InputAttribs;
import portfolio.dbHost.project.attributes.OptionalAttributes;
import portfolio.dbHost.project.attributes.TimeLine;
import portfolio.mainScreen;
import portfolio.menu.StockItems;

public class ProjectNew extends JInternalFrame implements ActionListener, MouseListener, Runnable
{
    private Host       host    = null;    
    private JTree      m_tree  = null;
    
    private mainScreen mainFrame   = null;
    private JPanel     centerPanel = null;            
    private JPanel     panelList   = null;
    private JPanel     panelTree   = null;
    
    private JTextField jtProject      = null;
    private JTextField inputDBaseText = null;
    private JComboBox  excludeTables  = null;
    private JTextField indexColumn    = null;
    private JComboBox  excludeCols    = null;
    private JTextField trainVarColumn = null;
    
    private JComboBox  yearBox        = null;
    private JComboBox  monthBox       = null;
    private JComboBox  dayBox         = null;
    private JComboBox  yearEndBox     = null;
    private JComboBox  monthEndBox    = null;
    private JComboBox  dayEndBox      = null;
    
    private JTextField termText       = null;
    private JTextField stockIndexText = null;
    private JTextField riskFreeText   = null;
    
    private String     sGlobalProjectName = null;

    static final String  ACTION_SELECT     = "vkAction_Select";
    static final String  ACTION_CANCEL     = "vkAction_Cancel";
    static final String  ACTION_ERASE      = "vkAction_Erase";
    
    private Thread      monitorProjectFlags;
    private boolean     terminateMonitorProject = true;
    private Column      columnTemp              = null;
    private Table       tableTemp               = null;
    private DBase       dBaseTemp               = null;
    
    /**
     *
     */
    public void run() 
    {
        String  sCurrentProjectName = null;
        
        Project project = host.getProject();
        if (project != null) {
//            boolean bProjectFlag = project.getProjectFlag();
//            if (bProjectFlag == false)
//                bProjectFlag = true;

            String sProject = host.getProject().getProjectName();
            dBaseTemp = host.getDB (sProject);
            dBaseTemp.setProjectFlag(true);

        } 
        while (terminateMonitorProject == true) {
            try {
//                if (project != null) {
//                    boolean bProject = project.getProjectFlag();
//                }
                if (Project.isProject(host.getDB(sGlobalProjectName))) { //host.getConnection(), sGlobalProjectName)) { //host.isProject (sGlobalProjectName)) {
                    if (!sCurrentProjectName.equals(sGlobalProjectName)) {
                        dBaseTemp = host.getDB (sGlobalProjectName); 
                        dBaseTemp.setProjectFlag (true);
                    }
                }
                sCurrentProjectName = sGlobalProjectName;
                if (dBaseTemp != null) {
                    if (dBaseTemp.getProjectFlag() == true) {
                        this.cleanProjectAttributes();

                        if (this.processProject () == false) {
                            mainFrame.displayMessage("ProjectNew.run 117", "Error: there are no parameters available on de projectDB.");
                        }
                        
                        dBaseTemp.setProjectFlag(false);
                    } else if (dBaseTemp.getInputDBFlag() == true) {
                        this.processInputDB ();
                        dBaseTemp.setInputDBFlag(false);
                    }
                }                
                if (tableTemp != null) {
                    if (tableTemp.getExcludeTableFlag () == true) {
                        this.processExcludeTable();
                        tableTemp.setExcludeTableFlag(false);
                    }                     
                } 
                if (columnTemp != null) {
                    if (columnTemp.getIndexFlag()   == true) {
                        this.processIndexCol();                            
                        columnTemp.setIndexFlag(false);
                    } else if (columnTemp.getExcludeFlag() == true) {
                        this.processExcludeCols();
                        columnTemp.setExcludeFlag(false);
                    } else if (columnTemp.getTrainSetFlag()  == true) {
                        this.processTrainVariable ();
                        columnTemp.setTrainSetFlag(false);
                    } else if (columnTemp.getOptPrjStock() == true) {
                        this.processOptAttribsStockIdx ();
                        columnTemp.setOptPrjStock (false);
                    } else if (columnTemp.getOptRiskFree () == true) {
                        this.processOptRiskFree ();
                        columnTemp.setOptRiskFree(false);
                    }
                }
                Thread.sleep (800);
                
                project = host.getProject();                
            } catch (InterruptedException e) {
                mainFrame.displayMessage("ProjectNew.run 152", e.toString());
                terminateMonitorProject = false;
                this.mainFrameSetEnabled (true);
                this.dispose();
            } catch (Exception e) {
//                int iLen = e.getStackTrace().length;
//                StackTraceElement stackTrace =  e.getStackTrace()[0];  //e.getCause().getStackTrace()[0];
//                e.printStackTrace();
//                mainFrame.displayErrorMsg (stackTrace, e.getMessage());
                mainFrame.displayMessage("ProjectNew.run 157", e.getMessage() + ". Handling of project name error.");
                terminateMonitorProject = false;
                this.mainFrameSetEnabled (true);
                this.dispose();
            }
        }
    }
    /**
     * Mouse listener abstract methods
     */
    public void mouseClicked  (MouseEvent evt) { }
    public void mousePressed  (MouseEvent evt) { }
    public void mouseReleased (MouseEvent evt) 
    { 
        Component cmpTemp = evt.getComponent();
        if (cmpTemp == null)
            return;

        int iXPos     = evt.getX();
        int iYPos     = evt.getY();
        JTree tmpTree = (JTree) cmpTemp;
        int iRow      = tmpTree.getRowForLocation (iXPos, iYPos);

        if (iRow == -1) {
            // do not report an error message here
            return;
        }

        if (!evt.isPopupTrigger()) {
            // error
            return;
        }

        TreePath selectPath = tmpTree.getPathForLocation (iXPos, iYPos);

        Object [] oTmpPath = selectPath.getPath();
        if (oTmpPath.length <= 0) {
            mainFrame.displayMessage("ProjectNew.mouseReleased 194", "error: wrong tree length.");
            return;
        }
        int iIdx = oTmpPath.length -1;
        
        try {
            Object oPopup = host.getTreeObject (oTmpPath);
//            String sClassName = oPopup.getClass().getName();
            String sClassName = oPopup.getClass().getSuperclass().getName();
            if        (sClassName.equals (Host.class.getName())) { // "portfolio.dbHost.Host"
                //((Host)   oPopup).getPopupOptions(dbaseTree, iXPos, iYPos);
            } else if (sClassName.equals (DBase.class.getName())) { // "portfolio.dbHost.dataBases.DBase"
                dBaseTemp = ((DBase)  oPopup);
                dBaseTemp.getProjectPopupOptions(m_tree, iXPos, iYPos);
            } else if (sClassName.equals (Table.class.getName())) { // "portfolio.dbHost.dataBases.dbTable.Table"
                tableTemp = ((Table) oPopup);
                tableTemp.getProjectPopupOptions (m_tree, iXPos, iYPos);
            } else if (sClassName.equals (Column.class.getName())) { // "portfolio.dbHost.dataBases.dbTable.tblColumn.Column"
                columnTemp = ((Column) oPopup);
                if (tableTemp == null) {
                    tableTemp = columnTemp.getDBTable();
                }
                columnTemp.getProjectPopupOptions (m_tree, iXPos, iYPos);
            } else {
                mainFrame.displayMessage("ProjectNew.mouseReleased 219", "error at jDBaseTree.");
            }
        } catch (Exception ex) {
            mainFrame.displayMessage("ProjectNew.mouseReleased 222", ex.toString());
        }                            
    }
    public void mouseEntered  (MouseEvent e) { }
    public void mouseExited   (MouseEvent e) { }
    /**
     *
     */
    public void actionPerformed (ActionEvent evt) 
    {
        String sSelProj = null;
        try {
            String sActionCommand = evt.getActionCommand ();

            if (sActionCommand.equals (ProjectNew.ACTION_SELECT)) {
                 sSelProj                  = this.jtProject.getText      ();

                 String    sTmpInputDB = this.inputDBaseText.getText (); //null;
                 String [] sExcludeTables  = this.getExcludeTables   (); //null;
                 String    sIndexColumn    = this.indexColumn.getText    ();
                 String [] sExcludeColumns = this.getExcludeColumns      ();
                 String    sTrainSetColumn = this.trainVarColumn.getText ();
                 Calendar  beginDate       = this.readBeginDate          ();
                 Calendar  endDate         = this.readEndDate            ();
                 Integer   ITerm           = this.readTerm               ();
                 String    sOptPrjStock    = this.readOptPrjStock        ();
                 String    sOptRiskFree    = this.readOptRiskFree        ();


//                 if (Project.isProject (host.getConnection(), sSelProj) == false) {
                 Project project = new Project (host, sSelProj);
                 project.initComponents (sTmpInputDB, sIndexColumn, sTrainSetColumn, beginDate, endDate, ITerm, sExcludeTables, sExcludeColumns, sOptPrjStock, sOptRiskFree);
//                } else {
//                }

                host.buildDBTree();
                host.updateDBTree();
                
                project.updateProjectTree();
                
                mainFrame.repaintStockTabedPanels ();

                StockItems stockItems = mainFrame.getStockItems();
                stockItems.updateStockItems(sTmpInputDB, sExcludeTables);
                
                this.mainFrameSetEnabled(true);
                mainFrame.displayMessage("ProjectNew.actionPerformed 345", "Project selected: " + sSelProj);

                this.terminateMonitorProject = false;
                sSelProj = null;
                
                this.dispose();
            } else if (sActionCommand.equals (ProjectNew.ACTION_CANCEL)) {

                this.terminateMonitorProject = false;
                this.mainFrameSetEnabled (true);
                mainFrame.displayMessage("ProjectNew.actionPerformed 355", "Project Cancel button selected.");
                this.dispose ();
            } else if (sActionCommand.equals(ProjectNew.ACTION_ERASE)) {
                this.cleanProjectAttributes ();
                columnTemp = null;
                tableTemp  = null;
                dBaseTemp  = null;
            }            
        } catch (Exception ex) {
            if (sSelProj != null) {
                try {
//0j0                    Connection connection = host.getConnection();
//0j0                    DBase.drop (connection, sSelProj);
                } catch (Exception exp) { 
//0j0 here                
                }
            }
            mainFrame.displayMessage("ProjectNew.actionPerformed 370", ex.getMessage());
        }
     } /* end method actionPerformed */
    /**
     *
     */
    public ProjectNew (Host hostParam) throws Exception       
    {
        super ("New Project.", false, true, false, false);
        mainFrame = hostParam.getMainScreen();
        host = hostParam;
        DefaultMutableTreeNode top = host.processTreeHierarchy();
        if (top != null) {
            this.mainFrameSetEnabled (false);
            
            this.setIconLogo();
            this.getContentPane ().setLayout (new BorderLayout ());
            mainFrame.getLayeredPane ().add (this);

            JPanel northPanel = new JPanel ();
            northPanel.setBorder (new EmptyBorder (5, 5, 0, 5));
            northPanel.setLayout (new BoxLayout (northPanel, BoxLayout.X_AXIS));
            JLabel fileLabel = new JLabel ("Project Name: ");
            northPanel.add (fileLabel);
    /////////////////////////////////////////        
            jtProject = new JTextField ();
            jtProject.addKeyListener (new KeyListener () {
                /**
                 * Keyboard listener abstract
                 */
                public void keyTyped(KeyEvent e) {}

                public void keyPressed(KeyEvent e) {}

                public void keyReleased(KeyEvent e) {
                    sGlobalProjectName = jtProject.getText();
                }
            }
            );
    /////////////////////////////////////////        
            northPanel.add (jtProject);
            this.getContentPane ().add ("North", northPanel);

            JPanel southPanel = new JPanel ( );
            southPanel.setLayout(new FlowLayout (FlowLayout.RIGHT));

            JButton btnSelect = new JButton ("Select");
            btnSelect.addActionListener (this);
            btnSelect.setActionCommand (ProjectNew.ACTION_SELECT);
            southPanel.add(btnSelect);

            JButton btnErase = new JButton("Erase");
            btnErase.addActionListener (this);
            btnErase.setActionCommand (ProjectNew.ACTION_ERASE);
            southPanel.add (btnErase);            

            JButton btnCancel = new JButton("Cancel");
            btnCancel.addActionListener (this);
            btnCancel.setActionCommand (ProjectNew.ACTION_CANCEL);
            southPanel.add (btnCancel);
            this.getContentPane ().add ("South", southPanel);

            centerPanel = new JPanel (new GridLayout (1, 2));
            centerPanel.setBorder(new EmptyBorder (5, 5, 5, 5));
        
            m_tree  = new JTree(top);
            m_tree.addMouseListener (this);

            panelTree = new JPanel ();
            panelTree.setLayout (new BoxLayout (panelTree, BoxLayout.Y_AXIS));
            panelTree.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "DB tree."));        
            JScrollPane scrollTree = new JScrollPane ();
            scrollTree.getViewport ().add (m_tree);

            m_tree.getSelectionModel ().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION);
            panelTree.add (scrollTree);

            panelList       = new JPanel ();
            panelList.setLayout(new BoxLayout (panelList, BoxLayout.Y_AXIS));
            panelList.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Project Attributes."));

            this.createInputDbBoxes      (panelList);            
            this.createDateRangeBoxes    (panelList);
            this.createTermBox           (panelList);
            this.createOptionalAttribBox (panelList);

            centerPanel.add (panelTree);
            centerPanel.add (panelList);

            this.getContentPane().add ("Center", centerPanel);            
            this.showThisFrame();
        
            monitorProjectFlags = new Thread (this);
            monitorProjectFlags.start();
            
            Rectangle recFrameBounds = new Rectangle ();
            recFrameBounds.x = this.getX();
            recFrameBounds.y = this.getY();
            recFrameBounds.width = this.getWidth();
            recFrameBounds.height = this.getHeight();
            
            recFrameBounds.height = recFrameBounds.height +40 + 40;
            this.setBounds(recFrameBounds);
            
        } else {
            throw new Exception ( " TreeNode error."); //<< 0j0 enhance this error message
        }       
    } /* end constructor SaveSqlDB */        
    /**
     *
     */
    public JTextField getProjectText ()
    {
        return jtProject;
    }
    /**
     *
     */
    public JTextField getInputDBText ()
    {
        return inputDBaseText;
    }
    /**
     *
     */
    public JTree getTree ()
    {
        return m_tree;
    }
    /**
     *
     */
    private void initDateRangeBoxes ()
    {
        yearBox.removeAllItems     ();
        monthBox.removeAllItems    ();
        dayBox.removeAllItems      ();
        yearEndBox.removeAllItems  ();
        monthEndBox.removeAllItems ();
        dayEndBox.removeAllItems   ();
        
        yearBox.addItem     ("----");
        monthBox.addItem    ("---");
        dayBox.addItem      ("--");
        yearEndBox.addItem  ("----");
        monthEndBox.addItem ("---");
        dayEndBox.addItem   ("--");            
    }
    /**
     *
     */
    private void createDateRangeBoxes (JPanel rangeArea)
    {
        rangeArea.setLayout (new BoxLayout (rangeArea, BoxLayout.Y_AXIS));
        this.getContentPane (). add (rangeArea, BorderLayout.CENTER);

        JPanel initRange = new JPanel ();
        initRange.setLayout (new FlowLayout (FlowLayout.CENTER));
        initRange.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Range Begin"));

        JLabel yearInitLabel = new JLabel ("Year");
        initRange.add (yearInitLabel);
        yearBox = new JComboBox ( );
        initRange.add (yearBox);

        JLabel monthInitLabel = new JLabel ("Month");
        initRange.add (monthInitLabel);
        monthBox = new JComboBox ();
        initRange.add (monthBox);

        JLabel dayInitLabel = new JLabel ("Day");
        initRange.add (dayInitLabel);
        dayBox = new JComboBox ();
        initRange.add (dayBox);

        rangeArea.add (initRange);

        JPanel finalRange = new JPanel ();
        finalRange.setLayout (new FlowLayout (FlowLayout.CENTER));
        finalRange.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Range End"));

        JLabel yearFinalLabel = new JLabel ("Year");
        finalRange.add (yearFinalLabel);
        yearEndBox = new JComboBox ();
        finalRange.add (yearEndBox);

        JLabel monthFinalLabel = new JLabel ("Month");
        finalRange.add (monthFinalLabel);
        monthEndBox = new JComboBox ();
        finalRange.add (monthEndBox);

        JLabel dayFinalLabel = new JLabel ("Day");
        finalRange.add (dayFinalLabel);
        dayEndBox = new JComboBox ();
        finalRange.add (dayEndBox);
        
        rangeArea.add (finalRange);

        this.initDateRangeBoxes ();        
    } /* End Method DateRange */
    /**
     *
     */
    private void repaintInputAttribsBoxes (Vector vInputAttribs) throws Exception
    {
        if (vInputAttribs == null) {
            throw new Exception ("Error: null sInputAttribs.");    
        }
        if (vInputAttribs.get(InputAttribs.INPUTATTRIBS_INPUTDB) == null) {
            throw new Exception ("Error: null sInputDB.");    
        }
        if (vInputAttribs.get(InputAttribs.INPUTATTRIBS_INDEXCOL) == null) {
            throw new Exception ("Error: null sInputDB.");    
        }
        if (vInputAttribs.get(InputAttribs.INPUTATTRIBS_INPUTDB).equals("")) {
            throw new Exception ("Error: null sInputDB.");    
        }
        if (vInputAttribs.get(InputAttribs.INPUTATTRIBS_INDEXCOL).equals("")) {
            throw new Exception ("Error: null sInputDB.");    
        }
        
        String sInputDB  = (String) vInputAttribs.get(InputAttribs.INPUTATTRIBS_INPUTDB);
        String sIndexCol = (String) vInputAttribs.get(InputAttribs.INPUTATTRIBS_INDEXCOL);
        String sTrainSet = (String) vInputAttribs.get(InputAttribs.INPUTATTRIBS_TRAINSET);
        
        inputDBaseText.setText(sInputDB);
        indexColumn.setText(sIndexCol);
        trainVarColumn.setText(sTrainSet);                                        
    }
    /**
     *
     */
    private void repaintExcludesCombos (Vector vExcludeTables, Vector vExcludeColumns) throws Exception
    {
        if (vExcludeTables == null) {
            mainFrame.displayMessage ("ProjectNew.repaintExcludesCombos 589", "Warning: ExcludeTables contains no elements.");
        } else {
            int iSize = vExcludeTables.size();
            if (iSize < 1) {
                mainFrame.displayMessage ("ProjectNew.repaintExcludesCombos 593", "Warning: ExcludeTables contains no elements.");
            } else {      
                excludeTables.removeAllItems();
                for (int i = 0; i < iSize; i++) {
                    excludeTables.addItem(vExcludeTables.get(i));
                }
            }
        }
        
        if (vExcludeColumns == null) {
            mainFrame.displayMessage ("ProjectNew.repaintExcludesCombos 603", "Warning: ExcludeColumns contains no elements.");
        } else {
            int iSize = vExcludeColumns.size();
            if (iSize < 1) {
                throw new Exception ("Error: ExcludeColumns contains no elements.");
            } else {
                for (int i = 0; i < iSize; i++) {
                    excludeCols.addItem (vExcludeColumns.get(i));    
                }
            }
        }
    }
    /**
     *
     */
    private boolean repaintDateRangeBoxes (Vector vTimeLine)
    {
        Calendar beginDateParam = (Calendar) vTimeLine.get(TimeLine.TIMELINE_BEGINDATE);
        Calendar endDateParam   = (Calendar) vTimeLine.get(TimeLine.TIMELINE_ENDDATE);
        
        if (beginDateParam == null) {
            this.initDateRangeBoxes();
            return false;
        }
        if (endDateParam == null) {
            this.initDateRangeBoxes();
            return false;
        }
        yearBox.removeAllItems();
        this.addYearItems (yearBox, beginDateParam, endDateParam);

        monthBox.removeAllItems();
        this.addMonthItems (monthBox);
        monthBox.setSelectedIndex (beginDateParam.get (Calendar.MONTH));

        dayBox.removeAllItems();
        this.addDayItems (dayBox, beginDateParam);

        yearEndBox.removeAllItems();
        Integer iIdx = this.addYearItems (yearEndBox, beginDateParam, endDateParam);
        yearEndBox.setSelectedItem (iIdx);

        monthEndBox.removeAllItems();
        this.addMonthItems (monthEndBox);
        monthEndBox.setSelectedIndex (endDateParam.get (Calendar.MONTH));

        dayEndBox.removeAllItems();
        this.addDayItems (dayEndBox, endDateParam);
        
        return true;
    } /* End Method DateRange */
    /**
     *
     */
    private void repaintTermBox (Vector vTimeLine)
    {
        if (vTimeLine == null) {
            termText.setText("---");
            return;
        }
        if (vTimeLine.size() != TimeLine.TIMELINE_SIZE){
            termText.setText("---");
            return;
        }
        if (vTimeLine.get(TimeLine.TIMELINE_TERM) == null){
            termText.setText("---");
            return;
        }

        Integer  ITermParam     = (Integer ) vTimeLine.get(TimeLine.TIMELINE_TERM);
        if (ITermParam != null) {
            termText.setText(ITermParam.toString ());
        } else {
            termText.setText("---");
        }
    }
    /**
     * Note: Due to the fact that OptionalAttributes are "optional", this method does not requires to terminate on error the newProject app in case that
     * there are no elements for Optional attributes.
     */
    private void repaintOptionalAttributes (Vector vOptionalAttribs) throws Exception {
        if (vOptionalAttribs == null){
            mainFrame.displayMessage("ProjectNew.repaintOptionalAttributes 608", "Warning: OptionalAttributes contains no elements.");
            return;
        }
        if (vOptionalAttribs.size() != OptionalAttributes.OPTIONALATTRIBS_SIZE) {
            mainFrame.displayMessage("ProjectNew.repaintOptionalAttributes 613", "Warning: wrong number of elements on OptionalAttributes.");
            return;
        }
        String sStockIndex = (String) vOptionalAttribs.get(OptionalAttributes.OPTIONALATTRIBS_SCTKIDX);
        if (sStockIndex.equals("")) {
            mainFrame.displayMessage("ProjectNew.repaintOptionalAttributes 618", "Warning: Stock Index optional attribute is empty.");            
        }
        String sRiskFree = (String) vOptionalAttribs.get(OptionalAttributes.OPTIONALATTRIBS_RSKFREE);
        if (sRiskFree.equals("")) {
            mainFrame.displayMessage("ProjectNew.repaintOptionalAttributes 618", "Warning: Risk Free optional attribute is empty.");            
        }
        stockIndexText.setText(sStockIndex);
        riskFreeText.setText(sRiskFree);
        
        return;
    }
    /**
     *
     */
    private Integer addYearItems (JComboBox yearItemParam, Calendar beginDateParam, Calendar endDateParam)
    {
        if (yearItemParam == null || beginDateParam == null || endDateParam == null)
            return null;

        Integer iIdx = null;
        for (int i = beginDateParam.get (Calendar.YEAR); i <= endDateParam.get (Calendar.YEAR); i++) {
            iIdx = new Integer (i);
            yearItemParam.addItem (iIdx);
        }

        return iIdx;
    }
    /**
     *
     */
    private void addMonthItems (JComboBox monthItemParam)
    {
        for (int i = 0; i <= Calendar.DECEMBER; i++) {
            monthItemParam.addItem (TimeLine.MONTHS_ARRAY_OBJECT [i]);
        }

        return;
    } /* end method addMonthItems */
    /**
     *
     */
    private void addDayItems (JComboBox dayItemParam, Calendar dateParam)
    {
        int iDaysInMonth = Miscellanea.getNumberOfDaysInMonth (dateParam);
        for (int i = 1; i <= iDaysInMonth; i++) {
            Integer daysInMonth = new Integer (i);
            dayItemParam.addItem (daysInMonth);
        }
        dayItemParam.setSelectedIndex (dateParam.get (Calendar.DAY_OF_MONTH) -1); 
        return;
    } /* end addDayItems */
    /**
     *
     */
    private int intSelectedMonth (String sMonth)
    {
        int iMonth = 0;
        for (int i = 0; i < 12; i++) {
            if (TimeLine.MONTHS_ARRAY_OBJECT [i].equals (sMonth)) {
                iMonth = i;
                break;
            }
        }
        return iMonth;
    } /* end method intSelectedMonth */        
    /**
     *
     */
    private void createTermBox (JPanel termArea)
    {
        JPanel infoArea = new JPanel ();
        infoArea.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Term"));

        termText = new JTextField ("--", 3);
        infoArea.add (termText);
        infoArea.add (new JLabel ("Records"));

        termArea.add (infoArea);
    }
    /**
     * 
     */
    private void createOptionalAttribBox (JPanel termArea)
    {
        JPanel optionalAttribsArea = new JPanel ();
        
        optionalAttribsArea.setLayout (new GridLayout (2, 2));            
        optionalAttribsArea.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Optional Attributes"));
        
        optionalAttribsArea.add (new JLabel ("Stock Index Variable"));
        stockIndexText = new JTextField (3);
        optionalAttribsArea.add (stockIndexText);

        optionalAttribsArea.add (new JLabel ("Risk Free Variable"));
        riskFreeText = new JTextField (3);
        optionalAttribsArea.add (riskFreeText);

        termArea.add (optionalAttribsArea);        
    }
    /**
     *
     */
    private void createInputDbBoxes (JPanel termArea)
    {
        JPanel inputDBArea = new JPanel ();
        inputDBArea.setLayout (new GridLayout (5, 2));            
        inputDBArea.setBorder (BorderFactory.createTitledBorder (new EtchedBorder (Color.white, Color.gray), "Input DB."));

        inputDBArea.add (new JLabel ("Input DBase: "));
        inputDBaseText = new JTextField (20);
        inputDBArea.add (inputDBaseText);
        inputDBArea.add (new JLabel ("Exclude Tables: "));
        excludeTables = new JComboBox ();
        inputDBArea.add (excludeTables);
        inputDBArea.add (new JLabel ("Index Column: "));
        indexColumn = new JTextField (20);
        inputDBArea.add (indexColumn);
        inputDBArea.add (new JLabel ("Exclude Cols: "));
        excludeCols = new JComboBox ();
        inputDBArea.add (excludeCols);
        inputDBArea.add (new JLabel ("Train Variable: "));
        trainVarColumn = new JTextField (20);
        inputDBArea.add (trainVarColumn);            

        termArea.add (inputDBArea);
    }
    /**
     *
     */
    private void showThisFrame ()
    {
        Miscellanea.showFrameInMidleScr (this, mainFrame, 300 +250, 305+50+50+20);                      
    }
    /**
     *
     */
    private void mainFrameSetEnabled (boolean bEnabled)
    {
        mainFrame.getMFile().setEnabled(bEnabled);
        host.getDBTree().getTree().setEnabled(bEnabled);
        if (bEnabled == true)
            host.getDBTree().getTree().addMouseListener(host.getDBTree());
        else
            host.getDBTree().getTree().removeMouseListener (host.getDBTree());
        mainFrame.getJTpaneLeft().setEnabled(bEnabled);
        mainFrame.getSplitPane2().setEnabled(bEnabled);            
    }
    /**
     *
     */
    private boolean processProject () throws Exception
    {
        String sDBName = dBaseTemp.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName); //dBaseTemp.isProject();
        if (bIsProject == true) { // is a projectDB?
            this.getProjectText ().setText(sDBName);
            
            String sProject = sDBName; //jtProject.getText ();
            Connection connection = host.getConnection();

            Vector vInputAttribs = InputAttribs.read   (connection, sProject);
            this.repaintInputAttribsBoxes (vInputAttribs);
            
            Vector vExcludeTables = ExcludeTables.read  (connection, sProject);
            Vector vExcludeColumns  = ExcludeColumns.read (connection, sProject);
            this.repaintExcludesCombos (vExcludeTables, vExcludeColumns);
            
            Vector    vTimeLine        =  TimeLine.read       (connection, sProject);
/*ACA NEW*/            if (vTimeLine == null) {
/*ACA NEW*/                return false;
/*ACA NEW*/            }
            this.repaintDateRangeBoxes (vTimeLine);
            this.repaintTermBox        (vTimeLine);
            
            Vector vOptionalAttribs    = OptionalAttributes.read (connection, sProject);
            this.repaintOptionalAttributes (vOptionalAttribs);
        } else {                  // is not a project? or is an inputDB?
             mainFrame.displayMessage("ProjectNew.processProject 811", "Warning: select a project type DB or create a new project DB.");
            return false;
        }                        
        return true;
    }
    /**
     *
     */
    private boolean processInputDB () throws Exception
    {
        String sDBName = dBaseTemp.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject /*dBaseTemp.isProject()*/ == false) {
//            String sDBName = dBaseTemp.getDBName();
            String sInputDBText = this.getInputDBText().getText();
            if (sInputDBText == null) {
                this.getInputDBText().setText(sDBName);
            } else {
                if (!sInputDBText.equals(sDBName)) {
                    this.getInputDBText().setText(sDBName);
                } else {
                    inputDBaseText.setText("");
                    inputDBaseText.repaint();
                }
            }
        } else {
            mainFrame.displayMessage("ProjectNew.processInputDB 835", "Warning: can't use a project as an input DB.");
            return false;
        }
        return true;
    }
    /**
     *
     */
    private boolean processExcludeTable () throws Exception
    {
        String sItemDB = tableTemp.getDBase().getDBName();
        String sItemTable = tableTemp.getTableName();
        boolean bIsProject = Project.isProject (host.getDB(sItemDB)); //host.getConnection(), sItemDB);
        if (bIsProject == false) { //!host.isProject(sItemDB)) {
            String [] sExcludeDBTables = this.getExcludeTables();
            boolean bExcludeDBTables = false;
            if (sExcludeDBTables != null) {
                int iSize = sExcludeDBTables.length;
                for (int i = 0; i < iSize; i++) {
                    if (sExcludeDBTables [i].equals(sItemTable)) {
                        bExcludeDBTables = true;
                    }
                }
            }
            
            if (bExcludeDBTables == false) {
                String sInputDB = this.inputDBaseText.getText();
                if (sInputDB == null || sInputDB.equals("")) {
                    this.inputDBaseText.setText(sItemDB);
                }
                excludeTables.addItem(sItemTable);
            } else {
                excludeTables.removeItem(sItemTable);
            }
        }                        
        return true;
    }
    /**
     *
     */
    private boolean processIndexCol () throws Exception
    {   
        String sIndexCol = columnTemp.getField ();
        DBase dBaseOfColumn = columnTemp.getDBTable().getDBase();
        String sDBName = dBaseOfColumn.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject/*dBaseOfColumn.isProject()*/) {
            mainFrame.displayMessage("ProjectNew.processIndexCol 878", "Warning: Can't use " + sIndexCol + " as index. It is a Project column.");
            return false;
        } 
        String sInputDB = columnTemp.getDBTable().getDBase().getDBName();
        String sInputDBText = this.inputDBaseText.getText();
        if (sInputDBText == null || sInputDBText.equals("")) {
            this.inputDBaseText.setText(sInputDB);
        } else if (!sInputDBText.equals(sInputDB)) {
            mainFrame.displayMessage("ProjectNew.processIndexCol 887", "Warning: The Index column " + sIndexCol + " comes from an input DB different than " +
                                      sInputDBText + ".");
            return false;                
        }
        if (sIndexCol == "") {
            indexColumn.setText(sIndexCol);
            excludeCols.addItem (sIndexCol);
        } else {
            String sColumn = indexColumn.getText();
            if (sColumn.equals(sIndexCol)) {
                indexColumn.setText("");
                excludeCols.removeAllItems();
                this.initDateRangeBoxes();          
            } else {
                indexColumn.setText(sIndexCol);
                excludeCols.removeAllItems();
                excludeCols.addItem (sIndexCol);
                
//                Connection connection = host.getConnection();
                Calendar [] extremeDates = Project.setExtremeIndexDates (host, sInputDB, sIndexCol); //connection, sInputDB, sIndexCol);
                Vector vExtremes = new Vector ();
                vExtremes.add(extremeDates[TimeLine.TIMELINE_BEGINDATE]);
                vExtremes.add(extremeDates[TimeLine.TIMELINE_ENDDATE]);
                this.repaintDateRangeBoxes (vExtremes);
            }
        }
        return true;
    }
    /**
     *
     */
    private boolean processExcludeCols () throws Exception
    {
        String sColumnTemp = columnTemp.getField();
        String sIndexColumn = indexColumn.getText();
        DBase dBaseOfColumn = columnTemp.getDBTable().getDBase();
        String sDBName = dBaseOfColumn.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject/*dBaseOfColumn.isProject()*/) {
            mainFrame.displayMessage("ProjectNew.processExcludeCols 918", "Warning: Can't use " + sColumnTemp + " as exclude. It is a Project column.");
            return false;
        }    
        if (sIndexColumn == null || sIndexColumn.equals("")) {
            mainFrame.displayMessage("ProjectNew.processExcludeCols 922", "Warning: please choose an index column before proseeding with excludeCols.");
            return false;
        }
        if (!sColumnTemp.equals(sIndexColumn)) {
            String [] sExcludeCols = this.getExcludeColumns();
            boolean bExcludeCol = false;
            if (sExcludeCols != null) {
                int iSize = sExcludeCols.length;
                for (int i = 0; i < iSize; i++) {
                    if (sExcludeCols [i].equals (sColumnTemp)) {
                        bExcludeCol = true;
                    }
                }
            }
            if (bExcludeCol == false) {
                excludeCols.addItem (sColumnTemp);
            } else {
                excludeCols.removeItem (sColumnTemp);
            }
        } else {
            mainFrame.displayMessage("ProjectNew.processExcludeCols 942", "Info: the column " + sColumnTemp + 
                                     " is used as an index and already accounted as exclude.");
        }
        return true;
    }
    /**
     *
     */
    private boolean processTrainVariable () throws Exception
    {
        String sColumnTemp = columnTemp.getField ();
        String sIndexColumn = indexColumn.getText();
        DBase dBaseOfColumn = columnTemp.getDBTable().getDBase();
        String sDBName = dBaseOfColumn.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject/*dBaseOfColumn.isProject()*/) {
            mainFrame.displayMessage("ProjectNew.processTrainSet 955", "Warning: Can't use " + sColumnTemp + " as Dependent Variable. It is a Project column.");
            return false;
        }    
        if (sIndexColumn == null || sIndexColumn.equals("")) {
            mainFrame.displayMessage("ProjectNew.processTrainSet 959", "Warning: please choose an index column before proseeding with Dependent Variable.");
            return false;
        }            
        if (sColumnTemp == "") {
            trainVarColumn.setText(sColumnTemp);
        } else {
            String sColumn = trainVarColumn.getText();
            if (sColumn.equals(sColumnTemp)) {
                trainVarColumn.setText("");
            } else {
                trainVarColumn.setText(sColumnTemp);
            }
        }
        return true;
    }
    /**
     * 
     */
    private boolean processOptAttribsStockIdx () throws Exception
    {
        String sColumnTemp = columnTemp.getField ();
        DBase dBaseOfColumn = columnTemp.getDBTable().getDBase();
        String sDBName = dBaseOfColumn.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject /*dBaseOfColumn.isProject()*/) {
            mainFrame.displayMessage("ProjectNew.processTrainSet 955", "Warning: Can't use " + sColumnTemp + " as Dependent Variable. It is a Project column.");
            return false;
        }
        
        stockIndexText.setText(sColumnTemp);
        return true;
    }
    /**
     * 
     */
    private boolean processOptRiskFree () throws Exception
    {
        String sColumnTemp = columnTemp.getField();
        DBase dBaseOfColumn = columnTemp.getDBTable().getDBase();
        String sDBName = dBaseOfColumn.getDBName();
        boolean bIsProject = Project.isProject (host.getDB(sDBName)); //host.getConnection(), sDBName);
        if (bIsProject/*dBaseOfColumn.isProject()*/) {
            mainFrame.displayMessage("ProjectNew.processTrainSet 955", "Warning: Can't use " + sColumnTemp + " as Dependent Variable. It is a Project column.");
            return false;
        }
        riskFreeText.setText (sColumnTemp);
        return true;
    }
    /**
     *
     */
    private Calendar readBeginDate () throws Exception
    {
        try {
            int iYearInit  = ((Integer) yearBox.getSelectedItem()).intValue();
            int iMonthInit = this.intSelectedMonth ((String) monthBox.getSelectedItem());
            int iDayInit = ((Integer) dayBox.getSelectedItem ()).intValue ();
            Calendar tmpBeginDate = Calendar.getInstance();
            tmpBeginDate.set (iYearInit, iMonthInit, iDayInit);
            
            return tmpBeginDate;
        } catch (Exception e) {
            throw new Exception (e + " BeginDate error.");
        }
    }
    /**
     *
     */
    private Calendar readEndDate () throws Exception
    {
        try {
            int iYearEnd  = ((Integer) yearEndBox.getSelectedItem()).intValue();
            int iMonthEnd = this.intSelectedMonth ((String) monthEndBox.getSelectedItem());
            int iDayEnd   = ((Integer) dayEndBox.getSelectedItem ()).intValue ();
            Calendar tmpEndDate = Calendar.getInstance();
            tmpEndDate.set (iYearEnd, iMonthEnd, iDayEnd); 

            return tmpEndDate;
        } catch (Exception e) {
            throw new Exception (e + " EndDate error.");
        }
    }
    /**
     *
     */
    private Integer readTerm () throws Exception
    {
        try {
            Integer ITmp = null;
            String sTmpTerm = termText.getText ();
            if (sTmpTerm != null) {
                ITmp = new Integer (sTmpTerm);
            }

            return ITmp;
        } catch (Exception e) {
            throw new Exception (e + " Term error.");
        }
    }
    /**
     * 
     */
    private String readOptPrjStock () throws Exception
    {
        try {
            String sStockIndex = stockIndexText.getText ();
            return sStockIndex;
        } catch (Exception e) {
            throw new Exception (e + " Optional Project Stock exception.");
        } 
    }
    /**
     * 
     */
    private String readOptRiskFree () throws Exception
    {
        try {
            String  sRiskFree = riskFreeText.getText ();
            return sRiskFree;
        }catch (Exception e) {
            throw new Exception (e + " Optional Risk Free exception.");
        }
    }
    /**
     *
     */
    private String [] getExcludeTables ()
    {
        int iSize = excludeTables.getItemCount();
        if (iSize < 1)
            return null;

        String [] sExcludeTables = new String [iSize];
        for (int i = 0; i < iSize; i++) {
            String sTable = (String) excludeTables.getItemAt(i);
            sExcludeTables [i] = new String (sTable);
        }
        return sExcludeTables;
    }
    /**
     *
     */
    private String [] getExcludeColumns (){    
        int iSize = excludeCols.getItemCount();
        if (iSize < 1)
            return null;

        String [] sExcludeCols = new String [iSize];
        for (int i = 0; i < iSize; i++) {
            String sTable = (String) excludeCols.getItemAt(i);
            sExcludeCols [i] = new String (sTable);
        }
        return sExcludeCols;
    }
    /**
     *
     */
    private void cleanProjectAttributes ()
    {
        jtProject.setText("");
        inputDBaseText.setText("");
        excludeTables.removeAllItems ();
        indexColumn.setText("");
        excludeCols.removeAllItems();
        trainVarColumn.setText("");
        this.initDateRangeBoxes();
        this.repaintTermBox (null);
        stockIndexText.setText("");
        riskFreeText.setText("");
    }
    /**
     * 
     */
    private void setIconLogo ()
    {    
        URL urlIconLogo = mainFrame.getURLIconLogo();
        
        if (urlIconLogo != null) {
            ImageIcon logoIcon = new ImageIcon (urlIconLogo);
            this.setFrameIcon(logoIcon);
        } else {
            mainFrame.displayMessage("ProjectNew.setIconLogo 1327", "can't read icon logo.");
        }        
    }
}